/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.message.controller;

import cn.icanci.basic.commonutils.R;
import cn.icanci.message.client.BaseDataServiceClient;
import cn.icanci.message.service.JavaMailByQqService;
import cn.icanci.message.utils.RegexPatterns;
import cn.icanci.message.utils.SendEmailUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.client.naming.utils.StringUtils;

/**
 * @author icanci
 * @date Created in 2021/04/28 11:11
 * @version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/message")
public class EmailMessageController {

    @Resource
    private JavaMailByQqService   javaMailByQqService;
    @Resource
    private BaseDataServiceClient baseDataServiceClient;

    @GetMapping("/getEmailCode/{email}")
    public R getMessageCode(@PathVariable("email") String email) {
        try {
            log.info("EmailMessageController getMessageCode,emailAddress:{}", email);
            // 正则表达式，判断邮箱
            String regexEmail = RegexPatterns.REGEX_EMAIL;
            Pattern compileEmail = Pattern.compile(regexEmail);
            Matcher matcherEmail = compileEmail.matcher(email);
            boolean matchesEmail = matcherEmail.matches();
            if (!matchesEmail) {
                return R.error().message("邮箱格式错误，请输入正确的邮箱");
            }
            String code = baseDataServiceClient.getCode(email);
            if (!StringUtils.isEmpty(code) && !"null".equals(code)) {
                log.warn("验证码已经存在，请查看你的邮箱,{}", code);
                return R.error().message("验证码已经存在，请查看你的邮箱").data("code", code);
            }
            code = SendEmailUtils.getRandomEmailCode();
            // 把email作为key,验证码作为 code，有效时间是5分钟
            baseDataServiceClient.setCode(email, code, 5 * 60);
            javaMailByQqService.sendMoreMail(SendEmailUtils.LOGIN_SUBJECT, SendEmailUtils.getManyMessage(code), SendEmailUtils.FROM, email);
        } catch (Exception e) {
            return R.error().message(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/cancelOrderEmail/{email}/{orderSerialNo}/{startCity}/{arriveCity}")
    public R cancelOrderEmail(@PathVariable("email") String email, @PathVariable("orderSerialNo") String orderSerialNo, @PathVariable("startCity") String startCity,
                              @PathVariable("arriveCity") String arriveCity) throws MessagingException {
        StringBuilder builder = new StringBuilder();
        builder.append("订单号：").append(orderSerialNo).append("，起飞城市：").append(startCity).append("，抵达城市：").append(arriveCity);
        javaMailByQqService.sendMoreMail(SendEmailUtils.CANCE_SUBJECT, SendEmailUtils.getManyMessageCancelOrder(builder.toString()), SendEmailUtils.FROM, email);
        return R.ok().message("成功发送");
    }

    @GetMapping("/preOrderEmail/{email}/{orderSerialNo}/{startCity}/{arriveCity}")
    public R preOrderEmail(@PathVariable("email") String email, @PathVariable("orderSerialNo") String orderSerialNo, @PathVariable("startCity") String startCity,
                           @PathVariable("arriveCity") String arriveCity) throws MessagingException {
        StringBuilder builder = new StringBuilder();
        builder.append("订单号：").append(orderSerialNo).append("，起飞城市：").append(startCity).append("，抵达城市：").append(arriveCity);
        javaMailByQqService.sendMoreMail(SendEmailUtils.PRE_SUBJECT, SendEmailUtils.getManyMessageCancelOrder(builder.toString()), SendEmailUtils.FROM, email);
        return R.ok().message("成功发送");
    }

    @GetMapping("/bookOrderEmail/{email}/{orderSerialNo}/{startCity}/{arriveCity}")
    public R bookOrderEmail(@PathVariable("email") String email, @PathVariable("orderSerialNo") String orderSerialNo, @PathVariable("startCity") String startCity,
                            @PathVariable("arriveCity") String arriveCity) throws MessagingException {
        StringBuilder builder = new StringBuilder();
        builder.append("订单号：").append(orderSerialNo).append("，起飞城市：").append(startCity).append("，抵达城市：").append(arriveCity);
        javaMailByQqService.sendMoreMail(SendEmailUtils.BOOK_SUBJECT, SendEmailUtils.getManyMessageBookOrder(builder.toString()), SendEmailUtils.FROM, email);
        return R.ok().message("成功发送");
    }
}
